package com.laozhao.msas.util;

import java.util.Calendar;
import java.util.Date;

public class CalendarUtil {

	public static Calendar convertCalendar(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		return calendar;
	}

	public static int getMonthSpace(Date fromDate, Date endDate) {
		Calendar c1 = convertCalendar(fromDate);
		Calendar c2 = convertCalendar(endDate);
		return (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR))*12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
	}

	public static int getFullMonthSpace(Date fromDate, Date endDate) {
		Calendar c1 = convertCalendar(fromDate);
		Calendar c2 = convertCalendar(endDate);
		int month = (c2.get(Calendar.YEAR) - c1.get(Calendar.YEAR))*12 + c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
		if (c1.get(Calendar.DAY_OF_MONTH) > c2.get(Calendar.DAY_OF_MONTH)) {
			month -- ;
		}
		return month;
	}

	public static int getDaysSpace(Date fromDate, Date endDate) {
		return Long
				.valueOf(
						((endDate.getTime() - fromDate.getTime()) / 1000L / 24L / 60L / 60L))
				.intValue();
	}
	

	public static int[] getCalendarSpace(Date fromDate, Date endDate) {
		if (fromDate.after(endDate)) {
			return null;
		}
		int[] result = new int[3];
		Calendar c1 = convertCalendar(fromDate);
		int day1 = c1.get(Calendar.DAY_OF_MONTH);
		int month1 = c1.get(Calendar.MONTH);
		int year1 = c1.get(Calendar.YEAR);
		Calendar c2 = convertCalendar(endDate);
		int day2 = c2.get(Calendar.DAY_OF_MONTH);
		int month2 = c2.get(Calendar.MONTH);
		int year2 = c2.get(Calendar.YEAR);
		//count day
		if (day2 >= day1) {
			result[2] = day2 - day1;
		}else {
			month2 --;
			Calendar tmpCal = Calendar.getInstance();
			tmpCal.setTime(c2.getTime());
			tmpCal.set(Calendar.MONTH, month2);
			tmpCal.set(Calendar.DAY_OF_MONTH, day1);
			int days = getDaysSpace(tmpCal.getTime(), c2.getTime());
			result[2] = days;
		}
		//count month
		if (month2 >= month1) {
			result[1] = month2 - month1;
		}else {
			year2 --;
			result[1] = 12 + month2 - month1;
		}
		//count year
		result[0] = year2 - year1;
		return result;
	}

}
